//
//  MM_NetWorkTableTool.m
//  MallManage_IOS
//
//  Created by 张浩 on 2023/9/19.
//

#import "MM_NetWorkTableTool.h"

/*!
 *  缓存的策略：(如果 cacheTime == 0，将永久缓存数据) 也就是缓存的时间 以 秒 为单位计算
 *  分钟 ： 60
 *  小时 ： 60 * 60
 *  一天 ： 60 * 60 * 24
 *  星期 ： 60 * 60 * 24 * 7
 *  一月 ： 60 * 60 * 24 * 30
 *  一年 ： 60 * 60 * 24 * 365
 *  永远 ： 0
 */
static NSInteger const cacheTime = 60 * 60 * 24 * 7;

/* 数据 库 的位置 **/
#define KURLCachePath  [JH_FileTool pathOfResourceType:JH_ResourceTypeUrl]

@interface MM_NetWorkTableTool ()

@property (nonatomic,weak) FMDatabase *db;

@end

@implementation MM_NetWorkTableTool


- (instancetype)initWithDB:(FMDatabase*)db {
    
    if (self = [super init]) {
        
        self.db = db;
        if ([self.db open]) {
            NSString * createSql = @"CREATE TABLE IF NOT EXISTS MCData\
            ('id'  INTEGER PRIMARY KEY  AUTOINCREMENT,\
            'url'  TEXT NOT NULL ,\
            'data' BLOB NOT NULL ,\
            'savetime' DATE\
            )";
            BOOL createRes = [db executeUpdate:createSql];
            if (createRes) {
                NSLog(@"创建netWorkTable 成功");
            } else {
                NSLog(@"创建netWorkTable 失败 :%@",db.lastErrorMessage);
            }
        } else {
            NSLog(@"打开netWorkTable表失败");
        }
    }
    return self;
}

/* 插入缓存数据 **/
- (void)saveData:(NSData *)data url:(NSString *)url {
    
    FMResultSet *rs = [self.db executeQuery:@"SELECT * FROM MCData WHERE url = ?",url];
    if([rs next]){
        /* 存在 当前的 一个记录 就 更新 **/
        [self.db executeUpdate: @"UPDATE MCData SET data =?,savetime =? WHERE url = ?",data,[NSDate date],url];
    } else {
        /* 否则插入 **/
        [self.db executeUpdate:@"INSERT INTO MCData (url,data,savetime) VALUES (?,?,?)",url, data,[NSDate date]];
    }
}

/* 读取缓存数据 **/
- (void)cachedDataWithUrl:(NSString *)url
           cacheDataBlock:(void(^)(NSData *))cacheBlock {
    
    FMResultSet *resultSet = nil;
    NSData * data = nil;
    resultSet = [self.db executeQuery:@"SELECT * FROM MCData WHERE url = ?", url];
    // 遍历查询结果
    while (resultSet.next) {
        NSDate *  time = [resultSet dateForColumn:@"savetime"];
        NSTimeInterval timeInterval = -[time timeIntervalSinceNow];
        if(timeInterval > cacheTime &&  cacheTime!= 0){
            
            /* 缓存数据过期了 **/
            NSString *deleteSql = @"DELETE FROM MCData WHERE url= ?";
            [self.db executeUpdate:deleteSql,url];
        }else{
            data = [resultSet objectForColumnName:@"data"];
        }
    }
    if (cacheBlock) {
        cacheBlock(data);
    }
}

- (void)deleteCacheWithUrl:(NSString *)url withPara:(NSDictionary *)para {
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:para];
    dict[@"customer_id"]  = @"";
    dict[@"token"]        = @"";
//    dict[@"version_code"] = [JH_GlobalTool current_version];
    dict[@"platform"]     = @"ios";
    NSString * cacheUrl = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]; // ios7
//    cacheUrl = [MM_Http urlDictToStringWithUrlStr:url WithDict:dict];
    
    NSString *deleteSql = @"DELETE FROM MCData WHERE url= ?";
    [self.db executeUpdate:deleteSql,cacheUrl];
}
@end
